<?php
require 'PHPUnit/Framework.php';
require 'file/SFL.php';
class SFL_Test extends PHPUnit_Framework_TestCase {
    public function testCreate() {
        $f='/tmp/sfl_test'.rand(0,10000);
        $sfl=new SFL($f);
        $this->assertEquals(0,$sfl->count());
        $this->assertEquals(4,$sfl->getIndexPos());
        $this->assertEquals(4,filesize($f));
        unlink($f);
    }
    public function testMain() {
        $this->buildDataFile($f,$list);
        $list_str=implode('',$list);
        $len=strlen($list_str);

        $sfl=new SFL($f);
        $count=$sfl->count();
        $this->assertEquals(count($list),$count);

        $this->assertEquals($list_str,implode('',$sfl->get($count)));

        $i=0;
        foreach ($list as $str) {
            $this->assertEquals($list[$i],current($sfl->get(1,$i)));
            $this->assertEquals($list[$i],current($sfl->get(1,-$count+$i)));
            $this->assertEquals(true,$sfl->exist($list[$i]));
            $i++;
        }
        $sfl->delete('surf');
        $this->assertEquals(count($list)-1,$sfl->count());
        $this->assertEquals('chen',current($sfl->get(1)));
        $this->assertEquals('sf.net',current($sfl->get(1,6)));
        $this->assertEquals(substr($list_str,4),implode('',$sfl->get($count)));
        $this->assertEquals($len+$count*3+4-4-3,filesize($f));

        $sfl->delete(chr(0));
        $this->assertEquals(count($list)-2,$sfl->count());
        $this->assertEquals('chen',current($sfl->get(1)));
        $this->assertEquals('sf.net',current($sfl->get(1,5)));

        unlink($f);
    }
    private function buildDataFile(&$f,&$list) {
        $f='/tmp/sfl_test'.rand(1,10000);
        $sfl=new SFL($f);

        $list = array(
            'surf','chen','.org','$@$%%#$%^#%^',chr(0),'',"\n\r\n\t",'sf.net'
            //'surf','chen','.org','sf.net'
        );
        foreach ($list as $str) {
            $sfl->add($str);
        }        
        unset($sfl);
    }
}
